const wxCharts = require('../../utils/wxcharts-min');
//引入工具类
const util = require('../../utils/util');
// 加载配置文件
const config = require('../../utils/config');

const app = getApp();

var lineChart = null;

let option = {
  canvasId: 'lineCanvas',
  type: 'line',
  categories: [''],
  animation: true,
  legend: false,
  series: [{
    data: [''],
    format: function (val, name) {
      return val + ' m³';
    }
  }],
  xAxis: {
    disableGrid: false,
    type: 'calibration'
  },
  yAxis: {
    title: '水量单位: 立方米(m³)',
    min: 0,
    gridColor: '#D8D8D8'
  },
  width: 0,
  height: 0,
  dataLabel: false,
  dataPointShape: true,
  extra: {
    lineStyle: 'curve'
  }
}

Page({
  data: {
    defaultEndDate: util.getDate(0),
    dataType: '',
    sDate: '',
    eDate: '',
    active: 2,
    defaultDate: 30,
    chartsData: {
      xData: [],
      yData: []
    },
    isShowChart: true,
    noData: 'loading...',
    orginXData: [],
    listData: [],
    searVal: '',
    pageTitle: '',
    title: '',
    meterAddress: ''
  },
  inputSearVal(e) {
    this.setData({
      searVal: e.detail.value
    })
  },
  setDefaultTime(type) {
    this.setData({
      searVal: ''
    })
    option.type = 'line'
    option.dataLabel = false
    if (type == 0) {
      option.type = 'column'
      option.dataLabel = true
      this.setData({
        dataType: 'year',
        sDate: util.getYear(-1).substring(0, 4),
        eDate: util.getYear(0).substring(0, 4)
      })
    } else if (type == 1) {
      this.setData({
        dataType: 'month',
        sDate: util.getMonth(-12).substring(0, 7),
        eDate: util.getMonth(0).substring(0, 7)
      })
    } else if (type == 2) {
      this.setData({
        dataType: 'day',
        sDate: util.getDate(-this.data.defaultDate),
        eDate: util.getDate(0)
      })
    }
  },
  compareTime: function (st, et) {
    console.log(util.timeDifference(st, et));
    if (this.data.active == 0) {
      if (st > et) {
        wx.showToast({
          title: '开始不能大于结束时间',
          icon: 'none',
          duration: 1500
        })
        return true;
      }
    } else {
      if (+new Date(st.replace(/-/g, "/")) > +new Date(et.replace(/-/g, "/"))) {
        wx.showToast({
          title: '开始不能大于结束时间',
          icon: 'none',
          duration: 1500
        })
        return true;
      }
    }

    if (this.data.active == 2 && (+new Date(et.replace(/-/g, "/")) - +new Date(st.replace(/-/g, "/")) > this.data.defaultDate * 24 * 60 * 60 * 1000)) {
      wx.showToast({
        title: `时间不能大于${this.data.defaultDate}天`,
        icon: 'none',
        duration: 1500
      })
      return true;
    }
    if (this.data.active == 1 && util.timeDifference(st, et)) {
      wx.showToast({
        title: '时间不能大于12月',
        icon: 'none',
        duration: 1500
      })
      return true;
    }
    if (this.data.active == 0 && (et - st > 5)) {
      wx.showToast({
        title: '时间不能大于5年',
        icon: 'none',
        duration: 1500
      })
      return true;
    }

    return false;
  },
  bindsDateChange: function (e) {
    this.setData({
      sDate: e.detail.value
    })
  },
  bindeDateChange: function (e) {
    this.setData({
      eDate: e.detail.value
    })
  },
  clearDate(startT, endT) {
    let st = '',
      et = '';
    if (this.data.active == 0) {
      st = startT + '-01-01 00:00:00'
      et = endT + '-12-31 23:59:59'
    } else if (this.data.active == 1) {
      var dateArray = endT.split("-");
      var dayCount = new Date(dateArray[0], dateArray[1], 0).getDate();
      var eTime = endT + '-' + dayCount + ' 23:59:59';

      st = startT + '-01 00:00:00'
      et = eTime
    } else if (this.data.active == 2) {
      st = startT + ' 00:00:00'
      et = endT + ' 23:59:59'
    }
    return {
      st,
      et
    }
  },
  getDetailData() {
    if (this.compareTime(this.data.sDate, this.data.eDate)) {
      return;
    }
    wx.showLoading({
      title: '加载中...'
    })
    this.setData({
      isShowChart: false,
      noData: 'loading...'
    });

    let SETime = this.clearDate(this.data.sDate, this.data.eDate)
    var params = {
      keyword: this.data.searVal,
      dateType: this.data.active + 1,
      startTime: SETime.st,
      endTime: SETime.et
    }
    var apiUrl = 'actual/searchMine';
    if (this.data.pageTitle == "读数查询") {
      apiUrl = 'meterread/searchMine';
      params.meterAddress = this.data.meterAddress
    }

    let _this = this;
    app.ajax({
      url: `${config.httpUrl}${apiUrl}`,
      method: 'get',
      data: params,
      callback: function (error, data) {
        wx.hideLoading();
        var data = data.data
        if (data.day) {
          var temp = [];
          var tempXData = data.day.map((item) => {
            return item.substring(0, 10)
          })
          for (var i = 0; i < tempXData.length; i++) {
            if (temp.indexOf(tempXData[i]) == -1) {
              temp.push(tempXData[i]);
            } else {
              temp.push('');
            }
          }
          _this.setData({
            'chartsData.xData': temp
          });
        } else {
          _this.setData({
            'chartsData.xData': data.year || data.month
          });
        }
        _this.setData({
          isShowChart: true,
          orginXData: data.year || data.month || data.day,
          'chartsData.yData': data.sumWater,
          listData: data.jsonList.list
        });
        if (_this.data.chartsData.xData.length == 0 || _this.data.chartsData.yData.length == 0) {
          _this.resetData();
        }
        _this.updateCharts(_this.data.chartsData.xData, _this.data.chartsData.yData)
      }
    })
  },
  resetData() {
    this.setData({
      'chartsData.yData': [''],
      'chartsData.xData': [''],
      listData: [],
      isShowChart: false,
      noData: '暂无数据'
    });
  },
  touchHandler: function (e) {
    var _this = this;
    var index = lineChart.getCurrentDataIndex(e);
    lineChart.showToolTip(e, {
      format: function (item) {
        return _this.data.orginXData[index] + ': ' + item.data
      }
    });
  },
  updateCharts(xData, yData) {
    lineChart.updateData({
      categories: xData,
      series: [Object.assign(option.series[0], {
        data: yData
      })],
      yAxis: Array.prototype.slice.call(yData).sort()[0] > 0 ? Object.assign(option.yAxis, {
        min: 0
      }) : Object.assign(option.yAxis, {
        min: Array.prototype.slice.call(yData).sort()[0]
      })
    });
  },
  onChange(e) {
    this.setDefaultTime(e.detail.index);
    this.setData({
      active: e.detail.index
    })
    this.getDetailData();
  },
  handleClick() {
    this.getDetailData();
  },
  onUnload() {
    this.resetData();
  },
  onLoad(options) {
    try {
      var res = wx.getSystemInfoSync();
      option.width = res.windowWidth / 750 * 750;
      option.height = res.windowWidth / 750 * 400;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    lineChart = new wxCharts(option);
    var _this = this;
    _this.setData({
      pageTitle: options.name,
      defaultDate: options.name == '用量查询' ? 30 : 10,
      meterAddress: options.meterAddress || '',
      title: options.title || ''
    })
    wx.setNavigationBarTitle({
      title: _this.data.pageTitle
    })
    this.setDefaultTime(this.data.active);

    this.getDetailData();
  },
  onShow() {
    let pages = getCurrentPages();
    let curPage = pages[pages.length - 1];
    app.checkBind(curPage.route);
  }
});